package com.jushu.storbox;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.manager.ActivityTaskManager;
import com.jushu.storbox.service.CloudDriveService;
import com.jushu.storbox.service.ICloudDriveService;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PollingAlarmUtils;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.view.viewImpl.SafeLockView;
import com.jushu.storbox.view.viewImpl.SafeLockView.OnCompleteListener;
import com.huawei.sharedrive.sdk.android.exception.ClientException;

public class LoackaActivity extends BaseActivity implements OnClickListener
{
	private SafeLockView lpwv;
	private Toast toast;
	private String LOG_TAG = "LoackaActivity";
	private final static int ONCONNECTCOMPLETE = 10;
	private ProgressDialog myDialog;
	private long mExitTime = 0l;
	/** cloud drive service */
	private ICloudDriveService shareDriveService;
	private TextView infoName,forgetPassword,switchingUser;
	private SharedPreferences settings ;
	/***
	 * seervice connection
	 */
	public ServiceConnection serviceConnection = new ServiceConnection() 
	{
		@Override
		public void onServiceConnected(ComponentName name, IBinder service)
		{
			LogUtil.i(LOG_TAG, "onServiceConnected()");
			shareDriveService = ((CloudDriveService.CenterShareDriveServiceServiceBinder) service).getService();
			if (null == shareDriveService) 
			{
				System.exit(0);
			} 
		}
		@Override
		public void onServiceDisconnected(ComponentName name)
		{
			shareDriveService = null;
			LogUtil.e(LOG_TAG, "onServiceDisconnected()");
		}
	};
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);  
		setContentView(R.layout.loack_layout);
		ActivityTaskManager.getInstance().putActivity(LOG_TAG,LoackaActivity.this);
		initView();
		bindservice();
	}
	private void showToast(CharSequence message) 
	{
		if (null == toast)
		{
			toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
		} 
		else 
		{
			toast.setText(message);
		}

		toast.show();
	}
	private void initView()
	{
		infoName = (TextView)findViewById(R.id.loack_user_info_name);
		forgetPassword = (TextView)findViewById(R.id.lock_forget_password);
//		switchingUser = (TextView)findViewById(R.id.lock_switching_user);
		lpwv = (SafeLockView) this.findViewById(R.id.mLocusPassWordView);
		initData();
		setListener();
	}
	private void initData()
	{
		infoName.setText(subStringStart(PublicTools.getClientUserName(getApplicationContext())));
		settings= LoackaActivity.this.getSharedPreferences(
				ClientConfig.settings, Context.MODE_APPEND);
	}
	private void setListener()
	{
		lpwv.setOnCompleteListener(new PasswordOnCompleteListener());
		forgetPassword.setOnClickListener(this);
		switchingUser.setOnClickListener(this);
	}
	@Override
	public void onClick(View view)
	{
		if(view.equals(forgetPassword))
		{
		}
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if(resultCode == 1)
		{
			unregister();
		}
	}
	private class PasswordOnCompleteListener implements OnCompleteListener
	{
		@SuppressLint("CommitPrefEdits")
		@Override
		public void onComplete(String password)
		{
			if (lpwv.verifyPassword(password))
			{
				{
					showToast(getApplicationContext().getResources().getString(R.string.unlock_success));
					Editor editor=settings.edit();
					editor.putBoolean(ClientConfig.AUTO_SAFETY_LOCK, false);
					editor.commit();
					finish();
				}
			} 
			else
			{
				showToast(getApplicationContext().getResources().getString(R.string.error_drawing_password));
				lpwv.clearPassword();
			}
		}
	}
	private void unregister()
	{
		myDialog = new ProgressDialog(LoackaActivity.this);
		myDialog.setMessage(LoackaActivity.this
				.getString(R.string.setting_activity_logouting));
		myDialog.show();
		myDialog.setCanceledOnTouchOutside(false);
		myDialog.setCancelable(false);
		new Thread(new Runnable() 
		{
			@Override
			public void run() 
			{
				String res = "";
				if (shareDriveService != null) 
				{
					Message msg = new Message();
					try
					{
						res = shareDriveService.logout();
						msg.what = 0;
					}
					catch (ClientException e) 
					{
						msg.what = 1;
					}
					handler.sendMessageDelayed(msg, 1500);
				}
			}
		}).start();
	}
	private String subStringStart(String str)
	{
		str.trim();
		int index = str.lastIndexOf(" ");
		if(index<0)
		{
			return str;
		}
		else
		{
			str = str.substring(0, index);
			str = str.trim();
			return str;
		}
	}
	private String subStringEnd(String str)
	{
		str.trim();
		int index = str.lastIndexOf(" ");
		if(index<0)
		{
			return "";
		}
		else
		{
			str = str.substring(index + 1, str.length());
			str = str.trim();
			return str;
		}
	}
	private Handler handler = new Handler() 
	{
		@SuppressLint("NewApi")
		public void handleMessage(android.os.Message msg) 
		{
			SharedPreferences settings = LoackaActivity.this.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
			Editor editor = settings.edit();
			switch (msg.what) 
			{
			case 0:
				editor.putString(ClientConfig.LOGINPASSWORD, "");
				editor.putBoolean(ClientConfig.AUTOLOGIN, false);
				editor.putBoolean(ClientConfig.AUTO_SAFETY_LOCK, false);
				editor.putString(ClientConfig.USERNAME, "");
				editor.commit();
				myDialog.cancel();
				showToast("Please login again");
				Intent intents = new Intent();
				intents.setClass(LoackaActivity.this, LoginActivity.class);
				ActivityTaskManager.getInstance().closeAllActivity();
				startActivity(intents);
				LoackaActivity.this.finish();
				break;
			case 1:
				editor.putString(ClientConfig.LOGINPASSWORD, "");
				editor.putBoolean(ClientConfig.AUTOLOGIN, false);
				editor.putBoolean(ClientConfig.AUTO_SAFETY_LOCK, false);
				editor.putString(ClientConfig.USERNAME, "");
				editor.commit();
				myDialog.cancel();
				Intent intent = new Intent();
				intent.setClass(LoackaActivity.this, LoginActivity.class);
				ActivityTaskManager.getInstance().closeAllActivity();
				startActivity(intent);
				LoackaActivity.this.finish();
			}
		}
	};
	private void bindservice() 
	{
		Intent intent = new Intent(LoackaActivity.this,
				CloudDriveService.class);
		intent.setAction("tokenAlarm");
		if (null != serviceConnection) 
		{
			bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
		}
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
		{
			if(!getIntent().getExtras().getBoolean("iscloseLoack"))
			{
				long currentTime = System.currentTimeMillis();
				if (currentTime - mExitTime > 2000) 
				{
					mExitTime = currentTime;
					showToast(LoackaActivity.this.getResources().getString(R.string.main_fragment));
				} 
				else
				{
					LoackaActivity.this.moveTaskToBack(true);
				}
				return false;
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	@Override
	protected void onDestroy()
	{
				LogUtil.i(LOG_TAG, "onDestroy()");
				if (null != shareDriveService) 
				{
					SharedPreferences settings = getSharedPreferences(ClientConfig.settings, MODE_APPEND);
					Editor editor = settings.edit();
					editor.putBoolean(ClientConfig.LOGIN_BACKGROUND, false);
					editor.commit();
				}
				if (null != serviceConnection)
					unbindService(serviceConnection);
				PollingAlarmUtils.stopPollingService(LoackaActivity.this, 1, "relogin");
				ActivityTaskManager.getInstance().removeActivity(LOG_TAG);
				super.onDestroy();
	}
	@Override
	protected void onStop()
	{
		super.onStop();
	}
}
